package com.link.base.tencent.corpwx.usertag.service;

import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.usertag.dao.mybatis.mapper.UserTagItemMapper;
import com.link.base.tencent.corpwx.usertag.model.UserTag;
import com.link.base.tencent.corpwx.usertag.model.UserTagItem;
import com.link.base.tencent.corpwx.usertag.util.UserTagUtil;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 成员标签-成员 
 *
 * @author 欧阳振强
 * @date 2020-01-06 10:53:25.0
 */
@Service
public class UserTagItemServiceImpl extends BasicServiceImpl<UserTagItem> implements UserTagItemService {
    /**标签状态-等待添加*/
    private static final String TAG_STATUS_WAIT_ADD = "waitAdd";
    /**标签状态-已添加*/
    private static final String TAG_STATUS_ALREADY_ADD = "alreadyAdd";
    /**标签状态-等待删除*/
    private static final String TAG_STATUS_WAIT_DEL = "waitDel";

    @Resource
    private UserTagItemMapper userTagItemMapper;
    @Resource
    private AgentService agentService;
    
    @Override
    public BasicMapper<UserTagItem> getBasicMapper() {
        return userTagItemMapper;
    }

    @Override
    public List<UserTagItem> opUserTagItemList(List<String> tagUserList, List<UserTagItem> userTagItemList) throws Exception {
        List<UserTagItem> userTagItems = new ArrayList<>();
        if (tagUserList == null) {
            tagUserList = new ArrayList<>();
        }
        if (userTagItemList == null) {
            userTagItemList = new ArrayList<>();
        }
        Map<String, String> tagUserListMap =
                tagUserList.stream().collect(Collectors.toMap(item -> item, item -> item));
        Map<String, UserTagItem> userTagItemListMap =
                userTagItemList.stream().collect(Collectors.toMap(item -> item.getUserId(), item -> item));
        for (String item: tagUserList) {
            UserTagItem mapItem = userTagItemListMap.get(item);
            if (mapItem == null) {
                // 企业微信存在，CRM不存在，标记为新增
                UserTagItem userTagItem = new UserTagItem();
                userTagItem.setUserId(item);
                userTagItem.setStatus(TAG_STATUS_WAIT_ADD);
                userTagItems.add(userTagItem);
            } else {
                // 企业微信存在，CRM存在，不做处理
            }
        }
        for (UserTagItem item: userTagItemList) {
            if (tagUserListMap.get(item.getUserId()) == null) {
                // 企业微信不存在，CRM存在，标记为删除
                item.setStatus(TAG_STATUS_WAIT_DEL);
                userTagItems.add(item);
            }
        }
        return userTagItems;
    }

    @Override
    public List<UserTagItem> getUserTagItemListByTag(UserTag userTag) throws Exception {
        return userTagItemMapper.getUserTagItemListByTag(userTag);
    }

    @Override
    public void delUserTagByHeadId(UserTag userTag) throws Exception {
        userTagItemMapper.delUserTagByHeadId(userTag);
    }

    @Override
    public void delTagUser(UserTagItem userTagItem) throws Exception {
        String status = userTagItem.getStatus();
        if (TAG_STATUS_WAIT_ADD.equals(status)) {
            // 处于等待添加状态的成员，删除只需删除CRM端
            userTagItemMapper.deleteById(userTagItem);
        } else if (TAG_STATUS_ALREADY_ADD.equals(status)) {
            // 处于已添加状态的成员，删除需要同时删除企业微信和CRM端
            String tagId = userTagItem.getTagId();
            if (StringUtils.isBlank(tagId)) {
                throw new BasicServiceException("删除标签成员，需传入标签ID！");
            } else {
                List<String> userIdList = new ArrayList<>();
                userIdList.add(userTagItem.getUserId());
                UserTagUtil.editTagUser(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), "del", tagId, userIdList, null);
                userTagItemMapper.deleteById(userTagItem);
            }
        } else {
            throw new BasicServiceException("非法标签成员状态！");
        }
    }

    @Override
    public void syncTagUserToWx(UserTagItem userTagItem) throws Exception {
        String status = userTagItem.getStatus();
        if (TAG_STATUS_WAIT_ADD.equals(status)) {
            String tagId = userTagItem.getTagId();
            if (StringUtils.isBlank(tagId)) {
                throw new BasicServiceException("成员所属标签尚未同步到企业微信，您可直接同步标签！");
            }
            List<String> userIdList = new ArrayList<>();
            userIdList.add(userTagItem.getUserId());
            UserTagUtil.editTagUser(agentService.getExistAccessToken(AgentIdUtil.CORPWX_ADDRESSBOOK_AGENTID), "add", tagId, userIdList, null);
            // 更新标签成员状态
            userTagItem.setStatus(TAG_STATUS_ALREADY_ADD);
            userTagItemMapper.update(userTagItem);
        } else {
            throw new BasicServiceException("非法标签成员状态！");
        }
    }

    @Override
    public List<UserTagItem> queryUnSelectUserListPage(UserTagItem userTagItem) throws Exception {
        return userTagItemMapper.queryUnSelectUserListPage(userTagItem);
    }
}